#-------------------------------------------------------------------------------
# Name:       audio_converter.py
# Purpose:    Convert text to audio files
#
# Authors:    Glenn Ramsey <glenn.ramsey@slidespeech.com>
#
# Copyright:  (c) Slidespeech Ltd 2012
# Licence:    MIT license
#-------------------------------------------------------------------------------
import sys
from concurrent import futures

from converter_error import ConverterError

if sys.platform.startswith("linux"):
    from audio_converter_linux import *
elif sys.platform.startswith("darwin"):
    from audio_converter_osx import *
elif sys.platform.startswith("win"):
    from audio_converter_windows import *
else:
    raise NotImplementedError()
    
def convertAudio(text, language, path, basename):

    inFileName = textToAudio(text, language, path, basename)
        
    outFileName = os.path.join(path, basename + '.ogg')
    ret = encodeOgg(path, inFileName, outFileName)
    if ret:
        raise RuntimeError("Could not generate audio, {0} failed".format(AudioConfig.oggEncoder))
    
    outFileName = os.path.join(path, basename + '.mp3')
    ret = encodeMp3(path, inFileName, outFileName)
    if ret:
        raise RuntimeError("Could not generate audio, {0} failed".format(AudioConfig.mp3Encoder))
    
    os.remove(inFileName)
    

def textToSpeech(textList, path, prefix):
    # textlist is a list of named tuples (text, language)
    
    try:
#        # Run the audio conversion serially
#        # (~1.0 seconds on MacBook Pro 8,1 for 4slide-presentation.odp)
#        for i, text in enumerate(textList, 1):
#            basename = "{0}{1}".format(prefix, i)
#            convertAudio(text.text, text.language, path, basename)
    
        # Run the audio conversion in parallel using threads
        # (~6.9 seconds on MacBook Pro 8,1 for 4slide-presentation.odp)
        # How many threads to use? Probably not more than the number of CPUs available.
        # How do we find this out?
        with futures.ThreadPoolExecutor(max_workers=len(textList)) as executor:
            fs = []
            for i, text in enumerate(textList, 1):
                basename = "{0}{1}".format(prefix, i)
                fs.append(executor.submit(convertAudio, text.text, text.language, path, basename))
                
            # reraise any exceptions that the futures caused    
            for future in futures.as_completed(fs):
                if future.exception() is not None:
                    raise future.exception()
        
    except Exception as e:
        ex = ConverterError("Audio conversion failed: {0}".format(e))
        ex.cause = e
        raise ex
    